package thread.zalan;


import java.util.concurrent.Exchanger;

class FillAndEmpty {
    Exchanger<Student> exchanger = new Exchanger<Student>();
    Student student1 = new Student("xieyaoyan", 1);
    Student student2 = new Student("yingyinglei", 2);

    class FillingLoop implements Runnable {

        public void run() {
            try {
                System.out.println(student1.getName() + " 收拾书包，走向另一个座位");
                student1 = exchanger.exchange(student1);
                System.out.println("换完座位了，当前座位是： " + student1);
            } catch (InterruptedException ex) {
                System.out.println("FillingLoop.run");
            }
        }
    }

    class EmptyingLoop implements Runnable {

        public void run() {
            try {
                System.out.println(student2.getName() + " 收拾书包，走向另一个座位");
                student2 = exchanger.exchange(student2);
                System.out.println("换完座位了，当前座位是： = " + student2);
            } catch (InterruptedException ex) {
                System.out.println("EmptyingLoop.run");
            }
        }
    }

    void start() {
        new Thread(new FillingLoop()).start();
        new Thread(new EmptyingLoop()).start();
    }

    public static void main(String[] args) {
        FillAndEmpty fillAndEmpty = new FillAndEmpty();
        fillAndEmpty.start();
    }
}

class Student {
    private String name;
    private int id;

    public Student() {
    }

    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", id=" + id + '}';
    }
}
